Vue.component('upload-images', {
    template: `<el-upload class="upload-demo" :show-file-list="false" accept="image/*" drag :on-change="upload" :auto-upload="false" action="" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件
            <el-slider :min="1" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
        </div>
    </el-upload>
    `,
    props: ['data', 'id'],
    data() {
        return {
            quality: 100,
        }
    },
    methods: {
        formatTooltip(val) {
            return '图片压缩比例：' + val + '%';
        },
        upload({ raw }) {
            const that = this;
            // console.log(raw);
            // console.log( raw.size / 1024 / 1024);
            new Compressor(raw, {
                quality: that.quality / 100,
                success(file) {
                    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt500K = file.size / 1024 / 1024 < 10;
                    if (!isJPGorPNG) {
                        that.$message({
                            message: '上传头像图片只能是 JPG/PNG 格式!',
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!isLt500K) {
                        that.$message({
                            message: '上传图片大小不能超过 10MB! 可压缩后上传',
                            type: 'warning'
                        })
                        return false;
                    }
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        $.ajax({
                            headers: requestHeaders('JSON'),
                            url: `${BASE_URL2}/generalBusiness/generalSaveFilesAsImage`,
                            type: 'POST',
                            data: JSON.stringify({
                                Data: e.target.result,
                                DataLength: file.size,
                                FileName: file.name
                            }),
                            complete: function (XMLHttpRequest) {
                                requestPretreatment(XMLHttpRequest);
                            },
                            success: function (Result) {
                                if (Result.Status == "success") {
                                    that.$message.success('上传成功')
                                    that.data.push({
                                        Base64: e.target.result,
                                        Picture_URL: Result.FileName,
                                        Picture_Type: 0,
                                        id: that.id
                                    })
                                } else {
                                    that.$message.error('上传失败')
                                }
                            },
                            error: function () {
                                that.$message.error("图片过大，可尝试压缩")
                            },
                            dataType: "json"
                        });
                    }
                },
            });
        }
    }
})
Vue.component('yl-upload1', {
    template: `<div>
    <div class="preview" style="width:100px;height:100px" v-if="Picture_URL">
        <el-image class="el-upload-list__item-thumbnail" style="width: 100px; height: 100px" :src="base64?Picture_URL:base + Picture_URL" fit="contain"></el-image>
        <span class="el-upload-list__item-actions" style="width:100px;height:100px">
            <span @click="handlePictureCardPreview(base64?Picture_URL:base + Picture_URL)"><i class="el-icon-zoom-in"></i></span>
            <span @click="handleRemove"><i class="el-icon-delete"></i></span>
        </span>
    </div>
    <el-upload id="group" :disabled="loading" v-else class="upload-demo" :show-file-list="false" :on-change="upload"
        list-type="picture-card" action="" accept="image/*" :auto-upload="false">
        <i slot="default" :class="loading?'el-icon-loading':'el-icon-plus'"></i>
        <div v-if="!unslider" class="el-upload__tip" slot="tip">
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
            <el-slider :min="1" style="width:148px" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" fit="contain" :src="dialogImageUrl">
    </el-dialog></div>`,
    props: {
        value: {
            type: String,
            default: ''
        },
        base: {
            type: String,
            default: ''
        },
        base64: {
            type: Boolean,
            default: false
        },
        unslider:{
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            Picture_URL: this.value,
            loading: false,
            dialogVisible: false,
            dialogImageUrl: '',
            quality: 100,
        }
    },
    watch: {
        value(newVal) {
            this.Picture_URL = newVal
        },
        Picture_URL(newVal) {
            this.$emit('input', newVal);
        }
    },
    methods: {
        formatTooltip(val) {
            return '图片压缩比例：' + val + '%';
        },
        upload({ raw }) {
            const that = this;
            new Compressor(raw, {
                quality: that.quality / 100,
                success(file) {
                    that.loading = true;
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        if (!that.base64) {
                            $.ajax({
                                headers: requestHeaders("JSON"),
                                url: `${BASE_URL2}/generalBusiness/generalSaveFilesAsImage`,
                                type: 'POST',
                                data: JSON.stringify({
                                    Data: e.target.result,
                                    DataLength: file.size,
                                    FileName: file.name
                                }),
                                success: function (Result) {
                                    if (Result.Status == "success") {
                                        that.Picture_URL = Result.FileName
                                        that.$message.success('上传成功')
                                    } else {
                                        that.$message.error('上传失败')
                                    }
                                },
                                complete: function (XMLHttpRequest) {
                                    that.loading = false
                                    requestPretreatment(XMLHttpRequest);
                                },
                                dataType: "json"
                            });
                        } else {
                            that.Picture_URL = e.target.result;
                            that.loading = false
                        }
                    }
                },
                error(err) {
                    console.log(err.message);
                },
            });
        },
        handlePictureCardPreview(Val) {
            this.dialogVisible = true
            this.dialogImageUrl = Val
        },
        handleRemove() {
            this.Picture_URL = ''
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Article_SerialNumber: '',//商品主键
                Article_Name: '',//商品名称
                Article_Code: '',
                Staples_Code: '',
                Brand_SerialNumber: '',//商品品牌
                Category_SerialNumber: '',//商品类别
                Series_SerialNumber: '',//商品系列
                Item_SerialNumber: '',//商品款型
                Unit_Price: 0,//吊牌价
                Picture_URL: '',//封面图
                Unify_Unit_Price: '0',
                ClassifyJSON: '',
                JDCOM_Unit_Price: '',
                JDCOM_URL: '',
                Group: '否',
                Row_Status: '9',
                Create_ID:$.cookie('user'),
                Children: {
                    business_article_specifications: [
                    //     {
                    //     Article_Specifications_SerialNumber: '',//规格主键
                    //     Article_SerialNumber: '',
                    //     Specifications_Name: '',//规格名称
                    //     Unit_Price: 0,//吊牌价
                    //     SKU_Quantity: '',//SKU数量
                    //     Picture_URL: '',//规格图片
                    //     Weight: '',//重量
                    //     Size: '',
                    //     Weight_Unit: '',//单位      
                    //     JDCOM_Unit_Price: '',//吊牌价
                    //     JDCOM_URL: '',//京东路径
                    //     Package_Quantity: '',//包装数量
                    //     SKU_Package_Size: '',//包装尺寸
                    //     Carton_Quantity: '',//大包装数量
                    //     Children_Specifications_SerialNumber: '',
                    //     Other: [{
                    //         Supplier_SerialNumber: '',
                    //         Sales_Unit_Price: '',
                    //         Purchase_Unit_Price: '',
                    //         Quantity: '',
                    //         Pionts: [],
                    //         Deduction_Type: '1',
                    //         Deduction_Limit: '100',
                    //         Activity: [{
                    //             Activity_SerialNumber: '',
                    //             Activity_Unit_Price: '',
                    //         }]
                    //     }]
                    // }
                    ],
                    business_article_pic: [],//商品图片
                    business_article_classify: [],
                }
            },
            rules: {
                Article_Name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                Brand_SerialNumber: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
                // Unit_Price: [{ required: true, message: '请输入商品吊牌价', trigger: 'change' }],
                Specifications_Name: [{ required: true, message: '请输入规格名称', trigger: 'blur' }],
                // SKU_Quantity: [{ required: true, message: '请输入SKU数量', trigger: 'blur' }]
            },
            Main_Image: [],
            Detail_Image: [],
            brand: [],//品牌
            category: [],//类别
            series: [],//系列
            item: [],//款型
            unit: [],//单位
            supplier: [],//供应商
            activity: [],//活动
            classify: [],
            business_article_classify: [],
            defaultProps: {
                children: 'Children',
                label: 'Classify_Name',
                value: 'Classify_SerialNumber',
                multiple: true,
            },
            loading: false,
            isMainSort: false,//主图排序
            isDetailSort: false,//详情图排序
            MainSortable: null,//主图拖拽
            DetailSortable: null,//详情图拖拽
            activeName: 0,//图片
            business_article_group: []
        }
    },
    mounted() {
        const elements = document.querySelectorAll('.el-descriptions-item__label');
        // 遍历每个元素
        for (let i = 0; i < elements.length; i++) {
            // 获取元素的innerHTML
            let html = elements[i].innerHTML;
            // 使用正则表达式替换所有的 * 为红色的 *
            html = html.replace(/\*/g, '<span style="color: red;">*</span>');
            // 将修改后的HTML重新赋值给元素
            elements[i].innerHTML = html;
        }
        this.getData();
        this.sortable(this, '#Main_Image', '.preview', this.Main_Image, 'MainSortable');
        this.sortable(this, '#Detail_Image', '.preview', this.Detail_Image, 'DetailSortable');
        this.business_article_group.push({
            Specification_Group_Name: '规格',
            Picture_URL:'',
            Children: {
                business_article_group_detail: [{
                    id:createUniqueString(),
                    Specification_Group_Detail_Name: ''
                }]
            }
        })
    },
    watch: {
        isMainSort(val) {
            this.MainSortable.option('disabled', !val);
        },
        isDetailSort(val) {
            this.DetailSortable.option('disabled', !val);
        },
        'form.Unit_Price': function (val) {
            if (this.form.Unify_Unit_Price == '1') {
                this.form.Children.business_article_specifications.forEach(item => {
                    item.Unit_Price = val;
                })
            }
        },
        'form.Unify_Unit_Price': function (val) {
            if (val == '1') {
                this.form.Children.business_article_specifications.forEach(item => {
                    item.Unit_Price = this.form.Unit_Price;
                })
            }
        },
        business_article_group: {
            handler(newVal) {
                let arr = [];
                newVal.forEach((item,index) => {
                    let business_article_group_detail = item.Children.business_article_group_detail.filter((i,id)=>index==0&&id==0||i.Specification_Group_Detail_Name)
                    if (business_article_group_detail.length > 0) {
                        arr.push(business_article_group_detail)
                    }
                })
                //计算笛卡尔积
                arr = cartesianProduct(arr);
                let business_article_specifications = [];
                arr.forEach(item => {
                    let obj = this.form.Children.business_article_specifications.filter(i=>i.Group_ID == JSON.stringify(item.map(obj => obj.id)))[0]
                    if (obj) {
                        business_article_specifications.push({
                            ...obj, Specifications_Name: 
                            item.map(obj => obj.Specification_Group_Detail_Name).join('-'),
                        });
                    } else {
                        business_article_specifications.push({
                            Article_Specifications_SerialNumber: '',//规格主键
                            Article_SerialNumber: '',
                            Specifications_Name: item.map(obj => obj.Specification_Group_Detail_Name).join('-'),//规格名称
                            Group_ID:JSON.stringify(item.map(obj => obj.id)),
                            Unit_Price: '',//吊牌价
                            SKU_Quantity: '',//SKU数量
                            Size: '',
                            Weight: '',//重量
                            Weight_Unit: '',//单位
                            JDCOM_Unit_Price: '',
                            Centralize_Purchase_Price:'',
                            Staples_Code:'',
                            Staples_Code1:'',
                            JDCOM_URL: '',
                            Package_Quantity: '',//包装数量
                            SKU_Package_Size: '',//包装尺寸
                            Carton_Quantity: '',//大包装数量
                            Children_Specifications_SerialNumber: '',
                            Other: [{
                                Supplier_SerialNumber: '',
                                Sales_Unit_Price: '',
                                Purchase_Unit_Price: '',
                                Quantity: '',
                                Pionts: [],
                                Deduction_Type: '1',
                                Deduction_Limit: '100',
                                Activity: [{
                                    Activity_SerialNumber: '',
                                    Activity_Unit_Price: '',
                                }]
                            }]
                        })
                    }
                })
                this.form.Children.business_article_specifications = business_article_specifications;
            },
            deep: true
        }
    },
    computed: {
        business_supplier_article() {
            let business_supplier_article = [];
            this.form.Children.business_article_specifications.forEach(item => {
                item.Other.filter(i => i.Supplier_SerialNumber).forEach(ite => {
                    business_supplier_article.push({
                        Supplier_Article_SerialNumber: '',
                        Article_Name: this.form.Article_Name,
                        Specifications_Name: item.Specifications_Name,
                        Brand_SerialNumber: this.form.Brand_SerialNumber,
                        Supplier_SerialNumber: ite.Supplier_SerialNumber,
                        Article_SerialNumber: '',
                        Article_Specifications_SerialNumber: '',
                        Shelf: '1',
                        Sales_Unit_Price: ite.Sales_Unit_Price,
                        Purchase_Unit_Price: ite.Purchase_Unit_Price,
                        Quantity: ite.Quantity,
                        Pionts: ite.Pionts,
                        Deduction_Type: ite.Deduction_Type,
                        Deduction_Limit: ite.Deduction_Limit,
                        Activity: ite.Activity
                    })
                })
            })
            return business_supplier_article;
        }
    },
    methods: {
        getData() {
            const that = this;
            const Condition = "Row_Status='0'";
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_brand',
                    Condition,
                },
                success: function (res) {
                    that.brand = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_category',
                    Condition,
                },
                success: function (res) {
                    that.category = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_series',
                    Condition,
                },
                success: function (res) {
                    that.series = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_item',
                    Condition,
                },
                success: function (res) {
                    that.item = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_supplier_info',
                    Condition,
                },
                success: function (res) {
                    that.supplier = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_article_unit',
                    Condition,
                },
                success: function (res) {
                    that.unit = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllClassify`,
                type: 'GET',
                success: function (data) {
                    that.classify = data
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_activity',
                    Condition: "Row_Status <> '1' AND End_Date > NOW()",
                },
                success: function (res) {
                    that.activity = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (!that.form.Article_Code) {
                        that.$confirm('当前商品未录入商品编号可能会影响商品唯一性，是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            that.add({});
                        }).catch(() => { });
                    } else {
                        that.add({ business_article_config: [{ Article_Code: this.form.Article_Code }] });
                    }
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        add(code) {
            const that = this;
            let obj = deepClone(that.form);
            obj.Children.business_article_group = that.business_article_group;
            this.loading = true;
            that.Main_Image.filter(i => i.id == 0).forEach((item, index) => {//主图
                obj.Children.business_article_pic.push({
                    Article_PicNumber: '',
                    Article_SerialNumber: '',
                    Picture_Type: '0',
                    Picture_Order: index + 1,
                    Picture_URL: item.Picture_URL
                })
            })
            that.Detail_Image.filter(i => i.id == 0).forEach((item, index) => {//详情图
                obj.Children.business_article_pic.push({
                    Article_PicNumber: '',
                    Article_SerialNumber: '',
                    Picture_Type: '1',
                    Picture_Order: index + 1,
                    Picture_URL: item.Picture_URL
                })
            })
            obj.ClassifyJSON = JSON.stringify(that.business_article_classify);
            that.business_article_classify.forEach(Array => {
                Array.forEach(i => {
                    if (!obj.Children.business_article_classify.some(j => j.Classify_SerialNumber == i)) {
                        obj.Children.business_article_classify.push({
                            Article_Classify_SerialNumber: '',
                            Article_SerialNumber: '',
                            Classify_SerialNumber: i,
                            Parent_SerialNumber: Array[0],
                        })
                    }
                })
            })
            //提交
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({
                        Add: {
                            business_article_info: [obj], ...code,
                            base_operation_log: [generateLog('添加商品主数据', '平台端操作', 'business_article_info', JSON.stringify({ Add: { business_article_info: [obj] } }))]
                        }
                    })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        if (that.business_supplier_article.length > 0) {
                            that.$message.success("商品添加成功,开始配置供应商");
                            that.submitSupplier();//提交供应商信息
                        } else {
                            that.loading = false;
                            that.$message.success("提交成功");
                            window.history.go(-1)
                        }
                    } else {
                        that.loading = false;
                        that.$message.error("提交失败，请稍后再试")
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitSupplier() {//提交供应商
            const that = this;
            let sql = "";
            this.business_supplier_article.forEach(item => {
                if (sql) {
                    sql = sql + "\r\nOR business_article_info.Article_Name = '" + item.Article_Name + "'"
                        + "\r\nAND business_article_specifications.Specifications_Name = '" + item.Specifications_Name + "'"
                        + "\r\nAND business_article_info.Brand_SerialNumber = '" + item.Brand_SerialNumber + "'"
                } else {
                    sql = " business_article_info.Article_Name = '" + item.Article_Name + "'"
                        + "\r\nAND business_article_specifications.Specifications_Name = '" + item.Specifications_Name + "'"
                        + "\r\nAND business_article_info.Brand_SerialNumber = '" + item.Brand_SerialNumber + "'"
                }
            })
            if (sql) {
                sql = `WHERE ${sql}`
            }
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data: {
                    SQLSerialNumber: 'A_business_article_specifications2',
                    Condition: '',
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(sql))),
                },
                success: function (Result) {
                    if (Result.length > 0) {
                        //执行添加
                        let business_supplier_article = that.business_supplier_article;
                        let base_operation_log = [];
                        business_supplier_article.forEach(item => {
                            let obj = Result.filter(i => i.Specifications_Name == item.Specifications_Name && i.Article_Name == item.Article_Name && i.Brand_SerialNumber == item.Brand_SerialNumber)[0]
                            item.Article_SerialNumber = obj.Article_SerialNumber;
                            item.Article_Specifications_SerialNumber = obj.Article_Specifications_SerialNumber;
                            item.Supplier_Article_SerialNumber = item.Supplier_SerialNumber + '-' + obj.Article_Specifications_SerialNumber;
                            //日志
                            base_operation_log.push(
                                generateLog('添加供应商经营商品', '平台端操作', 'business_supplier_article', JSON.stringify({ Add: { business_supplier_article: [item] } }))
                            )
                        })
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/generalBusiness/generalSave`,
                            type: 'POST',
                            data: {
                                Data: JSON.stringify({ Add: { business_supplier_article, base_operation_log } })
                            },
                            success: function (res) {
                                if (res.Status === 'success') {
                                    //添加采购价格单
                                    if (business_supplier_article.filter(i => !isNaN(i.Purchase_Unit_Price) && i.Purchase_Unit_Price > 0).length > 0) {
                                        that.$message.success("开始添加采购价格单");
                                        that.submitPurchase(business_supplier_article);
                                    } else if (business_supplier_article.filter(i => !isNaN(i.Sales_Unit_Price) && i.Sales_Unit_Price > 0).length > 0) {//添加销售价格单
                                        that.$message.success("开始添加销售价格单");
                                        that.submitSales(business_supplier_article);
                                    } else if (business_supplier_article.filter(i => !isNaN(i.Quantity) && i.Quantity > 0).length > 0) {
                                        that.$message.success("开始添加每日库存");
                                        that.submitStock(business_supplier_article);
                                    } else if (business_supplier_article.filter(i => i.Pionts.length > 0 && !isNaN(i.Deduction_Limit) && i.Deduction_Limit > 0).length > 0) {
                                        that.$message.success("开始配置积分方案");
                                        that.submitPointsConfig(business_supplier_article);
                                    } else if (business_supplier_article.filter(i => i.Activity.length > 0).length > 0) {
                                        that.$message.success("开始插入活动商品");
                                        that.submitActivityArticle(business_supplier_article);
                                    } else {
                                        that.loading = false;
                                        that.$message.success("提交成功");
                                        window.history.go(-1)
                                    }
                                } else {
                                    that.loading = false;
                                    that.$message.error("提交失败，请稍后再试")
                                }
                            },
                            complete: function (XMLHttpRequest) {
                                requestPretreatment(XMLHttpRequest);
                            },
                            dataType: "json"
                        })
                    } else {
                        that.loading = false;
                        that.$message.error("未知错误")
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitPurchase(business_supplier_article) {//添加采购价格单
            const that = this;
            let business_purchase_unitprice_detail = [];
            business_supplier_article.filter(i => !isNaN(i.Purchase_Unit_Price) && i.Purchase_Unit_Price > 0).forEach(item => {
                business_purchase_unitprice_detail.push({
                    Purchase_Unit_Price_Detail_SerialNumber: '',
                    Purchase_Unit_Price_SerialNumber: '',
                    Supplier_Article_SerialNumber: item.Supplier_Article_SerialNumber,
                    Brand_SerialNumber: item.Brand_SerialNumber,
                    Purchase_Unit_Price: item.Purchase_Unit_Price,
                    Row_Status:'2'
                })
            })
            let business_purchase_unitprice = [{
                Purchase_Unit_Price_SerialNumber: '',
                Start_Date: getYMDDate(),
                End_Date: '',
                Enterprise_Info_SerialNumber: '',
                Children: {
                    business_purchase_unitprice_detail,
                }
            }]
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({ Add: { business_purchase_unitprice } })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        // $.ajax({//更新今日执行单
                        //     headers: requestHeaders(),
                        //     url: `${BASE_URL2}/article/generateDailyArticlePurchasePrice`,
                        //     type: 'GET',
                        //     complete: function (XMLHttpRequest) {
                        //         if (XMLHttpRequest.status != 200) {
                        //             that.$message.error("每日销售价格执行单更新失败")
                        //         }
                                
                        //     },
                        // })
                        //添加销售价格单
                        if (business_supplier_article.filter(i => !isNaN(i.Sales_Unit_Price) && i.Sales_Unit_Price > 0).length > 0) {
                            that.$message.success("开始添加销售价格单");
                            that.submitSales(business_supplier_article);
                        } else if (business_supplier_article.filter(i => !isNaN(i.Quantity) && i.Quantity > 0).length > 0) {
                            that.$message.success("开始添加每日库存");
                            that.submitStock(business_supplier_article);
                        } else if (business_supplier_article.filter(i => i.Pionts.length > 0 && !isNaN(i.Deduction_Limit) && i.Deduction_Limit > 0).length > 0) {
                            that.$message.success("开始配置积分方案");
                            that.submitPointsConfig(business_supplier_article);
                        } else if (business_supplier_article.filter(i => i.Activity.length > 0).length > 0) {
                            that.$message.success("开始插入活动商品");
                            that.submitActivityArticle(business_supplier_article);
                        } else {
                            that.loading = false;
                            that.$message.success("提交成功");
                            window.history.go(-1)
                        }
                    } else {
                        that.loading = false;
                        that.$message.error("采购价格单提交失败")
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitSales(business_supplier_article) {//添加销售价格单
            const that = this;
            let business_sales_unitprice_detail = [];
            business_supplier_article.filter(i => !isNaN(i.Sales_Unit_Price) && i.Sales_Unit_Price > 0).forEach(item => {
                business_sales_unitprice_detail.push({
                    Sales_Unit_Price_Detail_SerialNumber: '',
                    Sales_Unit_Price_SerialNumber: '',
                    Supplier_Article_SerialNumber: item.Supplier_Article_SerialNumber,
                    Brand_SerialNumber: item.Brand_SerialNumber,
                    Supplier_SerialNumber: item.Supplier_SerialNumber,
                    Unit_Price: item.Sales_Unit_Price
                })
            })
            let business_sales_unitprice = [{
                Sales_Unit_Price_SerialNumber: '',
                Start_Date: getYMDDate(),
                End_Date: '',
                Enterprise_Info_SerialNumber: '',
                Children: {
                    business_sales_unitprice_detail,
                    business_sales_unitprice_storescope: [{
                        Sales_Unit_Price_StoreScope_SerialNumber: '',
                        Sales_Unit_Price_SerialNumber: '',
                        Store_SerialNumber: 'STORE0000000001'
                    }]
                }
            }]
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({ Add: { business_sales_unitprice } })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        $.ajax({//更新今日执行单
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/article/generateDailyArticleSalesPrice`,
                            type: 'GET',
                            complete: function (XMLHttpRequest) {
                                if (XMLHttpRequest.status != 200) {
                                    that.$message.error("每日销售价格执行单更新失败")
                                }
                                //添加每日库存
                                if (business_supplier_article.filter(i => !isNaN(i.Quantity) && i.Quantity > 0).length > 0) {
                                    that.$message.success("开始添加每日库存");
                                    that.submitStock(business_supplier_article);
                                } else if (business_supplier_article.filter(i => i.Pionts.length > 0 && !isNaN(i.Deduction_Limit) && i.Deduction_Limit > 0).length > 0) {
                                    that.$message.success("开始配置积分方案");
                                    that.submitPointsConfig(business_supplier_article);
                                } else if (business_supplier_article.filter(i => i.Activity.length > 0).length > 0) {
                                    that.$message.success("开始插入活动商品");
                                    that.submitActivityArticle(business_supplier_article);
                                } else {
                                    that.loading = false;
                                    that.$message.success("提交成功");
                                    window.history.go(-1)
                                }
                            }
                        })
                    } else {
                        that.loading = false;
                        that.$message.error("销售价格单提交失败")
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitStock(business_supplier_article) {//添加每日库存
            const that = this;
            let business_supplier_article_stock_detail = [];
            business_supplier_article.filter(i => !isNaN(i.Quantity) && i.Quantity > 0).forEach(item => {
                business_supplier_article_stock_detail.push({
                    Supplier_Article_Stock_Detail_SerialNumber: '',
                    Supplier_Article_Stock_SerialNumber: '',
                    Supplier_Article_SerialNumber: item.Supplier_Article_SerialNumber,
                    Brand_SerialNumber: item.Brand_SerialNumber,
                    Quantity: item.Quantity
                })
            })
            let business_supplier_article_stock = [{
                Supplier_Article_Stock_SerialNumber: '',
                Start_Date: getYMDDate(),
                End_Date: '',
                Enterprise_Info_SerialNumber: '',
                Children: {
                    business_supplier_article_stock_detail
                }
            }]
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({ Add: { business_supplier_article_stock } })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        $.ajax({//更新今日执行单
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/article/generateDailyInventory`,
                            type: 'GET',
                            complete: function (XMLHttpRequest) {
                                if (XMLHttpRequest.status != 200) {
                                    that.$message.error("每日库存执行单更新失败")
                                }
                                //添加积分配置
                                if (business_supplier_article.filter(i => i.Pionts.length > 0 && !isNaN(i.Deduction_Limit) && i.Deduction_Limit > 0).length > 0) {
                                    that.$message.success("开始配置积分方案");
                                    that.submitPointsConfig(business_supplier_article);
                                } else if (business_supplier_article.filter(i => i.Activity.length > 0).length > 0) {
                                    that.$message.success("开始插入活动商品");
                                    that.submitActivityArticle(business_supplier_article);
                                } else {
                                    that.loading = false;
                                    that.$message.success("提交成功");
                                    window.history.go(-1)
                                }
                            }
                        })
                    } else {
                        that.loading = false;
                        that.$message.error("每日库存单提交失败")
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitPointsConfig(business_supplier_article) {//添加积分配置
            const that = this;
            let business_points_detail_config = [];
            business_supplier_article.filter(i => i.Pionts.length > 0 && !isNaN(i.Deduction_Limit) && i.Deduction_Limit > 0).forEach(item => {
                business_points_detail_config.push({
                    Points_Detail_Config_SerialNumber: '',
                    Supplier_Article_SerialNumber: item.Supplier_Article_SerialNumber,
                    Gift_Point: item.Pionts.some(i => i == 'Gift') ? '0' : '1',
                    Sales_Point: item.Pionts.some(i => i == 'Sales') ? '0' : '1',
                    Cash_Point: item.Pionts.some(i => i == 'Cash') ? '0' : '1',
                    Activit_Point: item.Pionts.some(i => i == 'Activit') ? '0' : '1',
                    Deduction_Type: item.Deduction_Type,
                    Deduction_Limit: item.Deduction_Limit,
                    Combination: '1',
                })
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({ Add: { business_points_detail_config } })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        //插入活动商品
                        if (business_supplier_article.filter(i => i.Activity.length > 0).length > 0) {
                            that.$message.success("开始插入活动商品");
                            that.submitActivityArticle(business_supplier_article);
                        } else {
                            that.loading = false;
                            that.$message.success("提交成功");
                            window.history.go(-1)
                        }
                    } else {
                        that.$message.error("积分配置提交失败")
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitActivityArticle(business_supplier_article) {//插入活动商品
            const that = this;
            let business_activity_article = [];
            business_supplier_article.forEach(item => {
                item.Activity.filter(i => i.Activity_SerialNumber && !isNaN(i.Activity_Unit_Price) && i.Activity_Unit_Price > 0).forEach(ite => {
                    business_activity_article.push({
                        Activity_Article_SerialNumber: '',
                        Activity_SerialNumber: ite.Activity_SerialNumber,
                        Supplier_Article_SerialNumber: item.Supplier_Article_SerialNumber,
                        Article_SerialNumber: '',
                        Article_Specifications_SerialNumber: item.Article_Specifications_SerialNumber,
                        Activity_Unit_Price: ite.Activity_Unit_Price,
                    })
                })
            })
            let base_operation_log = [generateLog('插入活动商品', '平台端操作', 'business_activity_article', JSON.stringify({ Add: { business_activity_article } }))];
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({ Add: { business_activity_article, base_operation_log } })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        that.$message.success("提交成功");
                        window.history.go(-1)
                    } else {
                        that.$message.error("插入活动商品提交失败")
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        add_article_specifications() {//添加规格
            this.business_article_group.push({
                Specification_Group_Name: '',
                Children: {
                    business_article_group_detail: [{
                        id:createUniqueString(),
                        Specification_Group_Detail_Name: ''
                    }]
                }
            })
            // this.form.Children.business_article_specifications.push({
            //     Article_Specifications_SerialNumber: '',//规格主键
            //     Article_SerialNumber: '',
            //     Specifications_Name: '',//规格名称
            //     Unit_Price: this.form.Unify_Unit_Price == '0' ? 0 : this.form.Unit_Price,//吊牌价
            //     SKU_Quantity: '',//SKU数量
            //     Size: '',
            //     Weight: '',//重量
            //     Weight_Unit: '',//单位
            //     JDCOM_Unit_Price: '',
            //     JDCOM_URL: '',
            //     Package_Quantity: '',//包装数量
            //     SKU_Package_Size: '',//包装尺寸
            //     Carton_Quantity: '',//大包装数量
            //     Children_Specifications_SerialNumber: '',
            //     Other: [{
            //         Supplier_SerialNumber: '',
            //         Sales_Unit_Price: '',
            //         Purchase_Unit_Price: '',
            //         Quantity: '',
            //         Pionts: [],
            //         Deduction_Type: '1',
            //         Deduction_Limit: '100',
            //         Activity: [{
            //             Activity_SerialNumber: '',
            //             Activity_Unit_Price: '',
            //         }]
            //     }]
            // })
        },
        remove_article_specifications() {//删除规格
            if (this.business_article_group.length > 1) {
                this.business_article_group.pop();
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
            // if (this.form.Children.business_article_specifications.length > 1) {
            //     this.form.Children.business_article_specifications.pop();
            // } else {
            //     this.$message({
            //         message: '不能在删除了',
            //         type: 'warning'
            //     })
            // }
        },
        add_Other(obj) {
            obj.Other.push({
                Supplier_SerialNumber: '',
                Sales_Unit_Price: '',
                Purchase_Unit_Price: '',
                Quantity: '',
                Pionts: [],
                Deduction_Type: '1',
                Deduction_Limit: '100',
                Activity: [{
                    Activity_SerialNumber: '',
                    Activity_Unit_Price: '',
                }]
            })
        },
        remove_Other(obj) {
            if (obj.Other.length > 0) {
                obj.Other.pop();
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        add_Activity(obj) {
            obj.Activity.push({
                Activity_SerialNumber: '',
                Activity_Unit_Price: '',
            })
        },
        remove_Activity(obj) {
            if (obj.Activity.length > 0) {
                obj.Activity.pop();
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        add_article_group_detail(item) {
            item.Children.business_article_group_detail.push({
                id:createUniqueString(),
                Specification_Group_Detail_Name: '',
            })
        },
        remove_article_group_detail(id, item) {
            item.Children.business_article_group_detail = item.Children.business_article_group_detail.filter((it, i) => i != id)
        },
        handleImgClick(formName) {//点击查看图片
            this.$refs[formName][0].showViewer = true;
        },
        RemoveImage(formName, index) {//删除图片
            this[formName].splice(index, 1);
        },
        sortable(that, container, element, jsonarray, className, callback) {//拖拽class配置
            var $ul = that.$el.querySelector(container)
            $ul.addEventListener('selectstart', function (e) {
                e.preventDefault();
            })
            this[className] = Sortable.create($ul, {
                handle: element,
                draggable: element,
                animation: 150,
                onUpdate: (event) => {
                    let newIndex = event.newIndex, oldIndex = event.oldIndex;
                    $li = $ul.children[newIndex],
                        $oldLi = $ul.children[oldIndex]
                    //先删除移动的节点, 再插入移动的节点到原有节点，还原了移动的操作
                    $ul.removeChild($li)
                    if (newIndex > oldIndex) {
                        $ul.insertBefore($li, $oldLi)
                    } else {
                        $ul.insertBefore($li, $oldLi.nextSibling)
                    }
                    //通过改变vue遍历数组移动节点
                    let item = jsonarray[oldIndex];
                    jsonarray.splice(oldIndex, 1);
                    jsonarray.splice(newIndex, 0, item);
                    if (callback) callback(newIndex, oldIndex);
                }
            })
            this[className].option('disabled', true);
        }
    }
})